// import { showInfoMsg, showErrorMsg } from '@/utils/popInfo'
import { ElMessage } from 'element-plus'
import { plcStore } from '@/store/plcStore'
import { storeToRefs } from 'pinia'
import handleWsMessage from '@/utils/wsMessage'
// const WS_API = 'ws://localhost:10087/websocket/ws'
const WS_API = 'ws://127.0.0.1:10086/socket/ws'
let socket = null
const store = plcStore()
let heart = null

export function initWebSocket (e:string) {
  const wsUri = WS_API + '/' + e
  socket = new WebSocket(wsUri)// 这里面的this都指向vue
  socket.onerror = webSocketOnError
  socket.onmessage = webSocketOnMessage
  socket.onclose = closeWebsocket
  ElMessage({
    message: 'WebSocket连接成功',
    type: 'success',
    duration: 2000
  })
  // heart = setInterval(() => {
  //   socket.send('xxx')
  // }, 3000)
}
export function webSocketOnError (e) {
  ElMessage({
    message: 'WebSocket连接发生错误' + e,
    type: 'error',
    duration: 2000
  })
}
export function webSocketOnMessage (e) {
  // console.log(e.data)

  handleWsMessage(e.data)
}
// 关闭websiocket
export function closeWebsocket () {
  console.log('连接已关闭...')
  // store.setWsStatus(false)
  clearTimeout(heart)
  heart = null
}
function close () {
  socket.close() // 关闭 websocket
  socket.onclose = function (e) {
    console.log(e)// 监听关闭事件
    console.log('关闭')
  }
}
export function webSocketSend (agentData) {
  socket.send(agentData)
}
